package com.yang.sso.oauth2.controller;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yang.common.core.result.BaseController;
import org.yang.common.core.result.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 公钥接口
 * @author: Islands
 * @create: 2024-03-23 15:35
 */

@Slf4j
@RestController
@RequestMapping("/rsa")
@RequiredArgsConstructor
public class RsaController extends BaseController {
    private final KeyPair keyPair;
    public static final String PUBLIC_KEY = "publicKey.key";


    /**
     * 获取公钥
     * @return R<Map<String, Object>>
     */
    @GetMapping("/publicKey")
    public R<Map<String, Object>> getPublicKey() {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAKey key = new RSAKey.Builder(publicKey).build();
        Map<String, Object> stringObjectMap = new JWKSet(key).toJSONObject();
        if(stringObjectMap.isEmpty()){
            return R.fail();
        }
        return R.success(stringObjectMap);
    }

    /**
     * 获取本地公钥
     * @return Result<String>
     */
    @GetMapping("/localKey")
    public R<String> getLocalKey(){
        try {
            Resource resource = new ClassPathResource(PUBLIC_KEY);
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
            BufferedReader br = new BufferedReader(inputStreamReader);
            return R.success(br.lines().collect(Collectors.joining("\n")));
        }catch (IOException e) {
            log.error("获取本地公钥失败:{}",e.getMessage());
            return R.fail();
        }

    }
}
